package online

import (
	"errors"
	"server/common"

	"github.com/mitchellh/mapstructure"
	"github.com/sirupsen/logrus"
)

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (s *OnlineService) checkStartProduceAckData(data common.P2PStartProduceAckData) error {
	// Check if call ID provided
	if data.CallId == "" {
		return errors.New("call_id cannot be empty in StartProduceAck")
	}

	// Check if user ID provided
	if data.UserId == "" {
		return errors.New("user_id cannot be empty in StartProduceAck")
	}

	// Check if call exists
	if !s.callMgr.CallExists(data.CallId) {
		return errors.New("call does not exist for call_id: " + data.CallId)
	}

	// Check if user exists
	if !s.userMgr.UserExists(data.UserId) {
		return errors.New("user client not found for user_id: " + data.UserId)
	}

	return nil
}

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (s *OnlineService) handleStartProduceAck(msg common.Message, from common.ServiceInfo,
	connId string) error {
	common.Logger(common.SERVICE_TYPE_ONLINE, msg.Rid).WithFields(logrus.Fields{
		"msg":    common.ToJson(msg),
		"from":   from,
		"connId": connId,
	}).Info("call handleStartProduceAck")

	var resData common.ResMsgData
	if err := mapstructure.Decode(msg.Data, &resData); err != nil {
		LOG(msg.Rid).WithError(err).Error("invalid start produce ack data format")
		return nil
	}

	var ackData common.P2PStartProduceAckData
	if err := mapstructure.Decode(resData.Data, &ackData); err != nil {
		LOG(msg.Rid).WithError(err).Error("invalid start produce ack data format")
		return nil
	}

	if err := s.checkStartProduceAckData(ackData); err != nil {
		LOG(msg.Rid).WithError(err).Error("invalid start produce ack data")
		return nil
	}

	if resData.Code != 0 {
		LOG(msg.Rid).Error("start produce ack failed")
	} else {
		LOG(msg.Rid).Info("start produce ack success")
	}

	return nil
}
